package com.taofuxn.yycreazy.mvp;


import com.taofuxn.yycreazy.retrofit.ApiClient;
import com.taofuxn.yycreazy.rxjava.SubscriberCallback;

import retrofit2.Retrofit;
import rx.Observable;
import rx.Scheduler;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * presenter 基类
 * Created by wanghuafu on 16/9/15.
 */
public class BasePresenter<V> implements Presenter<V> {


    public V mvpView;

    private CompositeSubscription mCompositeSubscription;

    protected Retrofit mRetrofit = ApiClient.mretrofit;


    @Override
    public void onAttachView(V mvpView) {
        this.mvpView = mvpView;
    }

    @Override
    public void onDetachView() {
        this.mvpView = null;
        unOnSubscriber();
    }

    /**
     * 移除观察者事件
     */
    private void unOnSubscriber() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

    /**
     * 添加观察者事件
     *
     * @param observable
     * @param mSubscriberCallback
     */
    public void addSubscription(Observable observable, Subscriber mSubscriberCallback) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }

        mCompositeSubscription.add(observable.
                subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread())
                .subscribe(mSubscriberCallback));
    }

}
